package com.example.demo2.student;
import com.example.demo2.Util.DBHelper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "loginServlet", value = "/loginServlet")
public class loginServlet extends HttpServlet {

    private DBHelper DBHelper;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String ID = request.getParameter("UID");
        String pwd = request.getParameter("upwd");
        boolean result = false;
        PreparedStatement preparedStatement = null;
        Connection conn = null;
        ResultSet rs = null;
        try {
            com.example.demo2.Util.DBHelper DBHelper = new DBHelper();
            conn = DBHelper.getConn();
            preparedStatement = conn.prepareStatement("select tid,password from webdesign.user where tid=? and password=?");
            preparedStatement.setString(1, ID);
            preparedStatement.setString(2, pwd);
            rs = preparedStatement.executeQuery();
            if (rs.next()) {
                result = true;
            }
        } catch (SQLException e) {
            response.setContentType("text/html;charest=UTF-8");
            response.setCharacterEncoding("utf-8");
            if (!result) {
                request.setAttribute("error", "loginError");
            } else {
                request.setAttribute("error", "nologinError");
            }
            DBHelper.closeAll(conn, preparedStatement, rs);


        }
        response.setContentType("text/html;charest=UTF-8");
        response.setCharacterEncoding("utf-8");
        if (!result) {
            request.setAttribute("error", "loginError");
        } else {
            request.setAttribute("error", "nologinError");
        }
        request.getRequestDispatcher("login.jsp").forward(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
